/*
 * @Description: 
 * @Author: zhihong deng
 * @Date: 2021-07-28 18:09:41
 * @LastEditors: zhihong deng
 * @LastEditTime: 2021-07-29 15:24:22
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home/index.vue'
import Login from '../views/Login/index.vue'
import Users from '../views/User/index.vue'
import UserAdd from '../views/User/add.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children:[
      {
        path: '/users',
        name: 'Users',
        component: Users
      },
      {
        path: '/useradd',
        name: 'Useradd',
        component: UserAdd
      }
    ]
    // 路由懒加载方式
    // component: () => import(/* webpackChunkName: "about" */ '../views/Home/index.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
]

const router = new VueRouter({
  routes
})

/*
在每一次的路由请求的时候，改方法都会执行，这个方法接收一个回调函数
to 将要前往的路由界面
from 代表来的地方
next 函数，代表是否放行
 */
router.beforeEach((to, from, next) => {
  console.log('to',to);
  console.log('from',from);
  console.log('next',next);
  next()
  if( to.path != '/login' && !localStorage.getItem('cmsToken')){
    next('/login');
    return;
  }else if( to.path == '/login' && localStorage.getItem('cmsToken')){
    next(from.path);
    return;
  }
})

export default router
